package com.software.levelupandroid.statistics;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.home.CallBack;
import com.software.levelupandroid.home.ui.taskByPriority.TaskByPriorityRepository;

import java.util.List;
public class TaskByMonthModel extends ViewModel {
    private final MutableLiveData<Resource<List<Task>>> taskListLiveData;
    public TaskByMonthModel(){
        taskListLiveData = new MutableLiveData<>();
    }

    public LiveData<Resource<List<Task>>> getTaskListLiveData(){
        return taskListLiveData;
    }


    //根据月份获取任务数据
    public void getTasksByMonth(Context context, String month){
        TaskByMonthRepository.getTaskByMonthRepository().getTaskByMonth(new CallBack<List<Task>>() {
            @Override
            //获取任务成功
            public void onSuccess(List<Task> data) {
                runOnMainThread(taskListLiveData, Resource.success(data));
            }

            @Override
            //获取task失败
            public void onFailure(String msg) {
                Log.e("home:", msg);
                runOnMainThread(taskListLiveData, Resource.failure(msg, null));
            }
        }, context, month);
    }

    private void runOnMainThread(MutableLiveData<Resource<List<Task>>> taskListLiveData, Resource<List<Task>> data) {
        if (Looper.myLooper() == Looper.getMainLooper())
            //当前线程在主线程
            taskListLiveData.setValue(data);
        else
            //当前线程不在主线程
            taskListLiveData.postValue(data);
    }


}
